<?php
// 应用公共文件
use think\facade\Cache;

function jsonFail($msg = '操作失败', $data = [], $code = 201, $extends = [])
{
    $compact = compact('code', 'msg', 'data');
    $compact = array_merge($compact, $extends);
    return json($compact);
}

function jsonSuccess($msg = '操作成功', $data = [], $code = 200, $extends = [])
{
    $compact = compact('code', 'msg', 'data');
    $compact = array_merge($compact, $extends);
    json($compact);
    return json($compact);
}

if (!function_exists('makeDualSql')) {
    /**生成dual的sql语句
     * @param $table
     * @param $data
     * @param $where
     * @return string
     */
    function makeDualSql($table, $data, $where)
    {
        $filed = '';
        $select = '';
        foreach ($data as $key => $value) {
            $filed .= "`{$key}`,";
            $select .= "'{$value}',";
        }
        $filed = trim($filed, ',');
        $select = trim($select, ',');
        $sql = "insert into `{$table}` ({$filed}) select {$select} from dual where $where";
        return $sql;
    }
}
if (!function_exists('oddEven')) {
    /**奇数做键偶数做值
     * @param $data
     * @return array
     */
    function oddEven($data)
    {
        $odd = [];
        $even = [];
        foreach ($data as $k => $v) {
            if ($k & 1) {
                $even[] = $data[$k];
            } else {
                $odd[] = $data[$k];
            }
        }
        return array_combine($odd, $even);
    }
}
if (!function_exists('TX_Map_Api_distance')) {
    /*
	 * 地图计算距离
	 *  $lat1:起点纬度
	 *  $lng1 : 起点经度
	 *  $lat2:终点纬度
	 *  $lng2 : 终点经度
	 * */
    function TX_Map_Api_distance($lat1, $lng1, $lat2, $lng2)
    {

        // 将角度转为狐度
        $radLat1 = deg2rad($lat1);// deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

        return $s;
    }
}
if (!function_exists('create_order_no')) {
    //生成订单号
    function create_order_no()
    {
        $order_no = date('Ymd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(1000, 9999));
        return $order_no;
    }
}
if (!function_exists('Transformation')) {
    //二维数组转一维数组
    function Transformation($array)
    {
        $result = array_reduce($array, function ($result, $value) {
            return array_merge($result, array_values($value));
        }, array());//转换得到商户ID
    }
}
if (!function_exists('Admin_find')) {
    //获取管理员信息
    function Admin_find($token)
    {
        $id = Cache::store('redis')->get($token);
        return \think\facade\Db::table('eb_admin')->where('id', $id)->find();
    }
}
if (!function_exists('Store_find')) {
    //获取管理员信息
    function Store_find($token)
    {
        $id = Cache::store('redis')->get($token);
        return \think\facade\Db::table('eb_store')->where('id', $id)->find();
    }
}
if (!function_exists('create_invite_code')) {
    //创建五位随机码
    function create_invite_code()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d')
            . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            $d = '',
            $f = 0;
            $f < 6;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }
}
if (!function_exists('Apply_refund')) {
    //组合打印机需要的数据
    function Apply_refund($A, $B, $C, $D)
    {
        $orderInfo = '--------------------------------<BR>';
        $orderInfo .= '<CB>大学食代</CB><BR>';
        $orderInfo .= '<CB>--用户协商退款通知--</CB><BR>';
        $orderInfo .= '<CB>--请尽快处理--</CB><BR>';
        $orderInfo .= '--------------------------------<BR>';
//        $orderInfo .= '期望送达时间：立即配送<BR>';
        return $orderInfo;
    }

}
if (!function_exists('combination_cancel')) {
    //组合打印机需要的数据
    function combination_cancel($money, $store, $order, $arr, $A, $B, $C, $D)
    {
        $orderInfo = '--------------------------------<BR>';
        $orderInfo .= '<CB>大学食代</CB><BR>';
        $orderInfo .= '<C>*' . $store['shop_name'] . '*</C><BR>';
        $orderInfo .= '<CB>--用户退款通知--</CB><BR>';
        $orderInfo .= '名称           单价  数量 金额<BR>';
        $orderInfo .= '--------------------------------<BR>';
//        $orderInfo .= '期望送达时间：立即配送<BR>';
        $orderInfo .= '下单时间：' . date("Y-m-d H:i", $order['create_time']) . '<BR>';
        foreach ($arr as $k5 => $v5) {
            $name = $v5['name'];
            $price = $v5['price'];
            $num = $v5['goods_num'];
            $prices = $v5['price'] * $v5['goods_num'];
            $kw3 = '';
            $kw1 = '';
            $kw2 = '';
            $kw4 = '';
            $str = $name;
            $blankNum = $A;//名称控制为14个字节
            $lan = mb_strlen($str, 'utf-8');
            $m = 0;
            $j = 1;
            $blankNum++;
            $result = array();
            if (strlen($price) < $B) {
                $k1 = $B - strlen($price);
                for ($q = 0; $q < $k1; $q++) {
                    $kw1 .= ' ';
                }
                $price = $price . $kw1;
            }
            if (strlen($num) < $C) {
                $k2 = $C - strlen($num);
                for ($q = 0; $q < $k2; $q++) {
                    $kw2 .= ' ';
                }
                $num = $num . $kw2;
            }
            if (strlen($prices) < $D) {
                $k3 = $D - strlen($prices);
                for ($q = 0; $q < $k3; $q++) {
                    $kw4 .= ' ';
                }
                $prices = $prices . $kw4;
            }
            for ($i = 0; $i < $lan; $i++) {
                $new = mb_substr($str, $m, $j, 'utf-8');
                $j++;
                if (mb_strwidth($new, 'utf-8') < $blankNum) {
                    if ($m + $j > $lan) {
                        $m = $m + $j;
                        $tail = $new;
                        $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                        $k = $A - strlen($lenght);
                        for ($q = 0; $q < $k; $q++) {
                            $kw3 .= ' ';
                        }
                        if ($m == $j) {
                            $tail .= $kw3 . ' ' . $price . ' ' . $num . ' ' . $prices;
                        } else {
                            $tail .= $kw3 . '<BR>';
                        }
                        break;
                    } else {
                        $next_new = mb_substr($str, $m, $j, 'utf-8');
                        if (mb_strwidth($next_new, 'utf-8') < $blankNum) continue;
                        else {
                            $m = $i + 1;
                            $result[] = $new;
                            $j = 1;
                        }
                    }
                }
            }
            $head = '';
            foreach ($result as $key => $value) {
                if ($key < 1) {
                    $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
                    $v_lenght = strlen($v_lenght);
                    if ($v_lenght == 13) $value = $value . " ";
                    $head .= $value . ' ' . $price . ' ' . $num . ' ' . $prices;
                } else {
                    $head .= $value . '<BR>';
                }
            }
            $orderInfo .= $head . $tail;
            @$nums += $prices;
        }
        $time = date('Y-m-d H:i:s', time());
        $orderInfo .= '--------------------------------<BR>';
        $orderInfo .= '商品费用：' . number_format($nums, 2) . '元<BR>';
        $orderInfo .= '退款费用：' . $money . '元<BR>';
        $orderInfo .= '配送费：' . $order['delivery_price'] . '元<BR>';
//        if($order['pay_type']==1){
//            $orderInfo .= '<B>支付方式：积分支付</B><BR>';
//        }else{
//            $orderInfo .= '<B>支付方式：余额支付</B><BR>';
//        }
        $orderInfo .= '<B>实付：' . $order['total_price'] . '</B><BR>';
        $orderInfo .= '<B>提货码:' . $order['code'] . '</B><BR>';
        $orderInfo .= '--------------------------------<BR>';
//        $orderInfo .= '<B>送货学校:'.$user['school_name'].'</B><BR>';
//        $orderInfo .= '<B>送货楼栋:'.$user['dormitory_name'].'</B><BR>';
//        $orderInfo .= '<B>送货地点:'.$user['address'].'</B><BR>';
//        $orderInfo .= '<B>收货电话:'.$user['phone'].'</B><BR>';
//        $orderInfo .= '<B>备注：'.$order['remark'].'<B><BR><BR>';
//        $orderInfo .= '<QR>http://dxsd.jlxmall.com/Wxlogin/login</QR>';//把解析后的二维码生成的字符串用标签套上即可自动生成二维码
//        $orderInfo .= '<CB>大学食代</CB><BR>';
        return $orderInfo;
    }

}
/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys 要排序的键字段
 * @param string $sort 排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
if (!function_exists('arraySort')) {
    function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}
if (!function_exists('combination')) {
    //组合打印机需要的数据
    function combination($store, $order, $arr, $A, $B, $C, $D, $type = 1)
    {
        $orderInfo = '--------------------------------';
        $orderInfo .= '<CB>校园顺代</CB>';
        $orderInfo .= '<C>*' . $store['shop_name'] . '*</C>';
        $orderInfo .= '-----------已在线支付-----------<BR>';
        $orderInfo .= '期望送达时间：立即配送<BR>';
        if ($type == 1) {
            $orderInfo .= '打印方式：正常打印,立即配送<BR>';
        } else {
            $orderInfo .= '打印方式：重复打印,请勿配送<BR>';
        }
        $orderInfo .= '下单时间：' . date("Y-m-d H:i", $order['create_time']) . '<BR>';
        $orderInfo .= '名称           单价  数量 金额<BR>';
        $orderInfo .= '--------------------------------<BR>';
        $arrs = arraySort($arr, 'type', SORT_ASC);
        foreach ($arrs as $k5 => $v5) {
            $name = $v5['name'];
            $price = $v5['price'];
            $num = $v5['goods_num'];
            $prices = $v5['price'] * $v5['goods_num'];
            $kw3 = '';
            $kw1 = '';
            $kw2 = '';
            $kw4 = '';
            $str = $name;
            $blankNum = $A;//名称控制为14个字节
            $lan = mb_strlen($str, 'utf-8');
            $m = 0;
            $j = 1;
            $blankNum++;
            $result = array();
            if (strlen($price) < $B) {
                $k1 = $B - strlen($price);
                for ($q = 0; $q < $k1; $q++) {
                    $kw1 .= ' ';
                }
                $price = $price . $kw1;
            }
            if (strlen($num) < $C) {
                $k2 = $C - strlen($num);
                for ($q = 0; $q < $k2; $q++) {
                    $kw2 .= ' ';
                }
                $num = $num . $kw2;
            }
            if (strlen($prices) < $D) {
                $k3 = $D - strlen($prices);
                for ($q = 0; $q < $k3; $q++) {
                    $kw4 .= ' ';
                }
                $prices = $prices . $kw4;
            }
            if ($v5['type'] == 2) {//套餐
                $meat_text = explode(',', $v5['meat_text']);
                $veg_text = explode(',', $v5['veg_text']);
                $meat_content = '荤菜:';
                $veg_content = '素菜:';
                $meat_Max_index = count($meat_text) - 1;
                $veg_Max_index = count($veg_text) - 1;
                foreach ($meat_text as $key => $v) {
                    if ($key != $meat_Max_index) {
                        $meat_content .= $v . '<BR>' . '     ';
                    } else {
                        $meat_content .= $v . '<BR>';
                    }
                }
                foreach ($veg_text as $key => $v) {
                    if ($key != $veg_Max_index) {
                        $veg_content .= $v . '<BR>' . '     ';
                    } else {
                        $veg_content .= $v . '<BR>';
                    }
                }
            } else {
                $meat_content = '';
                $veg_content = '';
            }
            for ($i = 0; $i < $lan; $i++) {
                $new = mb_substr($str, $m, $j, 'utf-8');
                $j++;
                if (mb_strwidth($new, 'utf-8') < $blankNum) {
                    if ($m + $j > $lan) {
                        $m = $m + $j;
                        $tail = $new;
                        $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                        $k = $A - strlen($lenght);
                        for ($q = 0; $q < $k; $q++) {
                            $kw3 .= ' ';
                        }
                        if ($m == $j) {
                            $tail .= $kw3 . ' ' . $price . ' ' . $num . ' ' . $prices;
                            if (!empty($veg_content)) {
//                                $tail .= '<L>'.$meat_content. '</L><BR>';
//                                $tail .= '<L>'.' ' .$veg_content. '</L><BR>';
                                $tail .= '<L>' . $meat_content . '</L>';
                                $tail .= '<L>' . $veg_content . '</L>';
                            }
                        } else {
                            $tail .= $kw3 . '<BR>';
                            if (!empty($veg_content)) {
                                $tail .= '<L>' . $meat_content . '</L>';
                                $tail .= '<L>' . ' ' . $veg_content . '</L>';
                            }
                        }
                        break;
                    } else {
                        $next_new = mb_substr($str, $m, $j, 'utf-8');
                        if (mb_strwidth($next_new, 'utf-8') < $blankNum) continue;
                        else {
                            $m = $i + 1;
                            $result[] = $new;
                            $j = 1;
                        }
                    }
                }
            }
            $head = '';
            foreach ($result as $key => $value) {
                if ($key < 1) {
                    $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
                    $v_lenght = strlen($v_lenght);
                    if ($v_lenght == 13) $value = $value . " ";
                    $head .= $value . ' ' . $price . ' ' . $num . ' ' . $prices;
                } else {
                    $head .= $value . '<BR>';
                }
            }
            $orderInfo .= $head . $tail;
            @$nums += $prices;
        }
        $time = date('Y-m-d H:i:s', time());
        $orderInfo .= '--------------------------------<BR>';
        $orderInfo .= '商品费用：' . number_format($nums, 2) . '元<BR>';
//        $orderInfo .= '服务费：' . $order['delivery_price'] . '元<BR>';
        $orderInfo .= '餐盒费：' . $order['lunchbox_price'] . '元<BR>';
        if ($order['is_raised'] == 1) {
            $orderInfo .= '配送费：' . ($order['floor_price'] + $order['delivery_price']). '元<BR>';
        }
        $orderInfo .= '实付：' . $order['total_price'] . '<BR>';
        if ($order['type'] == 1) {
            $orderInfo .= '配送模式:系统配送<BR>';
        } else {
            $orderInfo .= '配送模式:分配配送<BR>';
        }
        if ($order['is_raised'] == 1) {
            $orderInfo .= '提货方式:送货上楼<BR>';
        } else {
            $orderInfo .= '提货方式:楼栋自提<BR>';
        }
        $orderInfo .= '提货码:' . $order['code'] . '<BR>';
        $orderInfo .= '--------------------------------<BR>';
//        $orderInfo .= '<B>学校:'.$user['school_name'].'</B><BR>';
//        $orderInfo .= '<B>楼栋:'.$dormitory_info['name'].'</B><BR>';
        $orderInfo .= '地址:' . $order['dormitory_name'] . '-' . $order['floor_name'] . '-' . $order['address'] . '<BR>';
        $orderInfo .= '收货人:' . $order['name'] . '<BR>';
        $orderInfo .= '电话:' . $order['phone'] . '<BR>';
        $orderInfo .= '备注：' . $order['remark'] . '<BR>';
        $orderInfo .= '<QR>' . $order['order_no'] . '</QR>';//把解析后的二维码生成的字符串用标签套上即可自动生成二维码
//        $orderInfo .= '<CB>大学食代</CB><BR>';
        return $orderInfo;
    }

}
if (!function_exists('Send_msg')) {
    /**
     * @param $plat
     * @param $mobile
     * @param $template
     * @param array $extends
     * @return bool|string
     */
    function Send_msg($plat, $mobile, $template,$extends=[])
    {
        $nonceStr = substr(microtime(), -6);//生成6位
        $data = [
            'plat' => $plat,
            'mobile' => $mobile,
            'template' => $template,
            'extends' => json_encode($extends),
        ];
        ksort($data, SORT_STRING);
        $str = '';
        foreach ($data as $key => $value) {
            $str .= "{$key}={$value}&";
        }
        $str .= "nonceStr={$nonceStr}";
        $data['nonceStr'] = $nonceStr;
        $data['sign'] = md5($str);
        $url = 'http://service.jlxmall.com/shortMsg/send';
        $header = array(
            'Authorization:' . '123456'
        );
        // curl 初始化
        $curl = curl_init();
        // curl 设置
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 判断 $data get  or post
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 执行
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}
if (!function_exists('test_prints')) {
    //组合打印机需要的数据
    function test_prints($arr, $A, $B, $C, $D)
    {
        $orderInfo = '<CB>大学食代测试</CB><BR>';
        $orderInfo .= '名称           单价  数量 金额<BR>';
        $orderInfo .= '--------------------------------<BR>';
        foreach ($arr as $k5 => $v5) {
            $name = $v5['title'];
            $price = $v5['price'];
            $num = $v5['num'];
            $prices = $v5['price'] * $v5['num'];
            $kw3 = '';
            $kw1 = '';
            $kw2 = '';
            $kw4 = '';
            $str = $name;
            $blankNum = $A;//名称控制为14个字节
            $lan = mb_strlen($str, 'utf-8');
            $m = 0;
            $j = 1;
            $blankNum++;
            $result = array();
            if (strlen($price) < $B) {
                $k1 = $B - strlen($price);
                for ($q = 0; $q < $k1; $q++) {
                    $kw1 .= ' ';
                }
                $price = $price . $kw1;
            }
            if (strlen($num) < $C) {
                $k2 = $C - strlen($num);
                for ($q = 0; $q < $k2; $q++) {
                    $kw2 .= ' ';
                }
                $num = $num . $kw2;
            }
            if (strlen($prices) < $D) {
                $k3 = $D - strlen($prices);
                for ($q = 0; $q < $k3; $q++) {
                    $kw4 .= ' ';
                }
                $prices = $prices . $kw4;
            }
            for ($i = 0; $i < $lan; $i++) {
                $new = mb_substr($str, $m, $j, 'utf-8');
                $j++;
                if (mb_strwidth($new, 'utf-8') < $blankNum) {
                    if ($m + $j > $lan) {
                        $m = $m + $j;
                        $tail = $new;
                        $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                        $k = $A - strlen($lenght);
                        for ($q = 0; $q < $k; $q++) {
                            $kw3 .= ' ';
                        }
                        if ($m == $j) {
                            $tail .= $kw3 . ' ' . $price . ' ' . $num . ' ' . $prices;
                        } else {
                            $tail .= $kw3 . '<BR>';
                        }
                        break;
                    } else {
                        $next_new = mb_substr($str, $m, $j, 'utf-8');
                        if (mb_strwidth($next_new, 'utf-8') < $blankNum) continue;
                        else {
                            $m = $i + 1;
                            $result[] = $new;
                            $j = 1;
                        }
                    }
                }
            }
            $head = '';
            foreach ($result as $key => $value) {
                if ($key < 1) {
                    $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
                    $v_lenght = strlen($v_lenght);
                    if ($v_lenght == 13) $value = $value . " ";
                    $head .= $value . ' ' . $price . ' ' . $num . ' ' . $prices;
                } else {
                    $head .= $value . '<BR>';
                }
            }
            $orderInfo .= $head . $tail;
            @$nums += $prices;
        }
        $time = date('Y-m-d H:i:s', time());
        $orderInfo .= '--------------------------------<BR>';
        $orderInfo .= '合计：' . number_format($nums, 2) . '元<BR>';
        $orderInfo .= '送货地点：广州市南沙区xx路xx号<BR>';
        $orderInfo .= '联系电话：020-39004606<BR>';
        $orderInfo .= '订餐时间：' . $time . '<BR>';
        $orderInfo .= '备注：加辣<BR><BR>';
        return $orderInfo;
    }
}
if (!function_exists('my_scandir')) {

    function my_scandir($dir)
    {
        $files = array();//定义一个数组，做为返回值
        if (is_dir($dir))//判断路径是否存在
        {
            if ($handle = opendir($dir))//打开这个路径，并赋值给 handle 变量
            {
                while (($file = readdir($handle)) !== false)//用 readdir 读取路径，并且绝对不能为 false
                {
                    if ($file != "." && $file != "..")//返回的目录名称，不能是.或..,表示还有下一层目录，递归
                    {
                        if (is_dir($dir . "/" . $file))//将得到新的目录名称，判断是否存在，
                        {
                            $files[$file] = my_scandir($dir . "/" . $file);//存在就将路径再传递给 my_scandir 函数，进行新一轮读取
                        } else {
                            $files[] = $dir . "/" . $file;//不存在，表示目录下一级没有文件了，将当前路径返回
                        }
                    }
                }
                closedir($handle);//关闭路径
                return $files;
            }
        }
    }
}




